using UnityEngine;

[AddComponentMenu("Scripts/Area Damage/DestroyJoint")]
public class DestroyJoint : EventComponentArea<DestroyJoint>
{
	[Tooltip("Тело в соединении")]
	public Rigidbody2D body;

	[Tooltip("Второе тело")]
	public Rigidbody2D connectedBody;

	[Tooltip("Импульс для разброса тел из точки соединения в направлении центра массы тела")]
	public int impulse;

	[Tooltip("Добавить крутящий момент для двух указаных тел")]
	public float torque;

	private Joint2D[] listDestroy = new Joint2D[0];

	private AnchoredJoint2D anchoredJoint;

	public override bool ShowIconGizmos(AreaDamage area)
	{
		return body != null && connectedBody != null;
	}

	public override void Activation(AreaDamage area)
	{
		listDestroy = body.gameObject.GetComponents<Joint2D>();
		for (int i = 0; i < listDestroy.Length; i++)
		{
			if (listDestroy[i].connectedBody == connectedBody)
			{
				if (listDestroy[i] is AnchoredJoint2D)
				{
					anchoredJoint = (listDestroy[i] as AnchoredJoint2D);
				}
				else
				{
					UnityEngine.Object.Destroy(listDestroy[i]);
				}
			}
		}
		listDestroy = connectedBody.gameObject.GetComponents<Joint2D>();
		for (int j = 0; j < listDestroy.Length; j++)
		{
			if (listDestroy[j].connectedBody == body)
			{
				if (anchoredJoint == null && listDestroy[j] is AnchoredJoint2D)
				{
					anchoredJoint = (listDestroy[j] as AnchoredJoint2D);
				}
				else
				{
					UnityEngine.Object.Destroy(listDestroy[j]);
				}
			}
		}
		if ((impulse != 0 || torque != 0f) && anchoredJoint != null)
		{
			Vector2 vector = default(Vector2);
			Vector2 vector2 = default(Vector2);
			vector = anchoredJoint.transform.TransformPoint(anchoredJoint.anchor);
			Vector2 worldCenterOfMass = body.worldCenterOfMass;
			vector2.x = worldCenterOfMass.x - vector.x;
			Vector2 worldCenterOfMass2 = body.worldCenterOfMass;
			vector2.y = worldCenterOfMass2.y - vector.y;
			vector2.Normalize();
			vector2 *= impulse;
			body.isKinematic = false;
			body.AddForceAtPosition(vector2, vector);
			body.AddTorque(torque);
			Vector2 worldCenterOfMass3 = connectedBody.worldCenterOfMass;
			vector2.x = worldCenterOfMass3.x - vector.x;
			Vector2 worldCenterOfMass4 = connectedBody.worldCenterOfMass;
			vector2.y = worldCenterOfMass4.y - vector.y;
			vector2.Normalize();
			vector2 *= impulse;
			connectedBody.isKinematic = false;
			connectedBody.AddForceAtPosition(vector2, vector);
			connectedBody.AddTorque(0f - torque);
			UnityEngine.Object.Destroy(anchoredJoint);
		}
		if (onActivationListener != null)
		{
			onActivationListener(this);
		}
		UnityEngine.Object.Destroy(this);
	}
}
